<template>
  <div class="user-management-container">
    <h1>用户管理</h1>
    
    <div class="loading" v-if="loading">
      加载中...
    </div>
    
    <div class="error" v-else-if="error">
      {{ error }}
      <button @click="loadUsers">重新加载</button>
    </div>
    
    <div v-else>
      <div class="user-stats">
        共 {{ users.length }} 名用户
      </div>
      
      <div class="user-table-container">
        <table class="user-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>姓名</th>
              <th>性别</th>
              <th>年龄</th>
              <th>分数</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="user in users" :key="user.name">
              <td>{{ user.name }}</td>
              <td>{{ user.name }}</td>
              <td>{{ user.sex }}</td>
              <td>{{ user.age }}</td>
              <td>{{ user.score }}</td>
              <td>
                <button @click="editUser(user)" class="edit-btn">编辑</button>
                <button @click="deleteUser(user)" class="delete-btn">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
        
        <div v-if="users.length === 0" class="no-users">
          暂无用户数据
        </div>
      </div>
      
      <!-- 用户编辑模态框 -->
      <div v-if="showEditModal" class="modal-overlay" @click="closeEditModal">
        <div class="modal-content" @click.stop>
          <h2>{{ editingUser?.name ? '编辑用户' : '添加用户' }}</h2>
          <form @submit.prevent="saveUser">
            <div class="form-group">
              <label for="name">姓名:</label>
              <input 
                id="name" 
                v-model="userForm.name" 
                type="text" 
                required 
                :disabled="!!editingUser?.name"
              />
            </div>
            
            <div class="form-group">
              <label for="sex">性别:</label>
              <select id="sex" v-model="userForm.sex" required>
                <option value="男">男</option>
                <option value="女">女</option>
              </select>
            </div>
            
            <div class="form-group">
              <label for="age">年龄:</label>
              <input 
                id="age" 
                v-model.number="userForm.age" 
                type="number" 
                min="1" 
                max="150" 
                required 
              />
            </div>
            
            <div class="form-group">
              <label for="score">分数:</label>
              <input 
                id="score" 
                v-model.number="userForm.score" 
                type="number" 
                min="0" 
                max="100" 
                required 
              />
            </div>
            
            <div class="modal-actions">
              <button type="submit" :disabled="isSaving">
                {{ isSaving ? '保存中...' : '保存' }}
              </button>
              <button type="button" @click="closeEditModal" :disabled="isSaving">
                取消
              </button>
            </div>
          </form>
        </div>
      </div>
      
      <!-- 删除确认模态框 -->
      <div v-if="showDeleteModal" class="modal-overlay" @click="closeDeleteModal">
        <div class="modal-content" @click.stop>
          <h2>确认删除</h2>
          <p>确定要删除用户 "{{ userToDelete?.name }}" 吗？此操作不可撤销。</p>
          <div class="modal-actions">
            <button @click="confirmDelete" class="delete-btn" :disabled="isDeleting">
              {{ isDeleting ? '删除中...' : '确认删除' }}
            </button>
            <button @click="closeDeleteModal" :disabled="isDeleting">
              取消
            </button>
          </div>
        </div>
      </div>
      
      <div class="add-user-button">
        <button @click="addUser">添加用户</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { Student } from '@/services/api'

// 响应式数据
const users = ref<Student[]>([])
const loading = ref(true)
const error = ref('')
const showEditModal = ref(false)
const showDeleteModal = ref(false)
const editingUser = ref<Student | null>(null)
const userToDelete = ref<Student | null>(null)
const isSaving = ref(false)
const isDeleting = ref(false)

// 用户表单数据
const userForm = reactive({
  name: '',
  sex: '男',
  age: 18,
  score: 100
})

// 加载用户列表
const loadUsers = async () => {
  loading.value = true
  error.value = ''
  
  try {
    // 模拟从API获取数据
    // 实际使用时应该替换为真实的API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟用户数据
    users.value = [
      { name: '张三', sex: '男', age: 20, score: 90 },
      { name: '李四', sex: '女', age: 19, score: 85 },
      { name: '王五', sex: '男', age: 21, score: 95 },
      { name: '赵六', sex: '女', age: 22, score: 88 }
    ]
  } catch (err) {
    error.value = '加载用户列表失败'
    console.error('加载用户列表时出错:', err)
  } finally {
    loading.value = false
  }
}

// 添加用户
const addUser = () => {
  editingUser.value = null
  userForm.name = ''
  userForm.sex = '男'
  userForm.age = 18
  userForm.score = 100
  showEditModal.value = true
}

// 编辑用户
const editUser = (user: Student) => {
  editingUser.value = user
  userForm.name = user.name
  userForm.sex = user.sex
  userForm.age = user.age
  userForm.score = user.score
  showEditModal.value = true
}

// 保存用户（添加或更新）
const saveUser = async () => {
  isSaving.value = true
  
  try {
    // 模拟保存到API
    // 实际使用时应该替换为真实的API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (editingUser.value) {
      // 更新现有用户
      const index = users.value.findIndex(u => u.name === editingUser.value!.name)
      if (index !== -1) {
        users.value[index] = { ...userForm }
      }
    } else {
      // 添加新用户
      users.value.push({ ...userForm })
    }
    
    closeEditModal()
  } catch (err) {
    console.error('保存用户时出错:', err)
    alert('保存用户失败')
  } finally {
    isSaving.value = false
  }
}

// 删除用户
const deleteUser = (user: Student) => {
  userToDelete.value = user
  showDeleteModal.value = true
}

// 确认删除用户
const confirmDelete = async () => {
  if (!userToDelete.value) return
  
  isDeleting.value = true
  
  try {
    // 模拟从API删除数据
    // 实际使用时应该替换为真实的API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 从列表中移除用户
    users.value = users.value.filter(u => u.name !== userToDelete.value!.name)
    
    closeDeleteModal()
  } catch (err) {
    console.error('删除用户时出错:', err)
    alert('删除用户失败')
  } finally {
    isDeleting.value = false
  }
}

// 关闭编辑模态框
const closeEditModal = () => {
  showEditModal.value = false
  editingUser.value = null
}

// 关闭删除模态框
const closeDeleteModal = () => {
  showDeleteModal.value = false
  userToDelete.value = null
}

// 组件挂载时加载数据
onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.user-management-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

h1 {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
}

.loading, .error, .no-users {
  text-align: center;
  padding: 40px 20px;
  font-size: 18px;
}

.error {
  color: #d32f2f;
}

.error button {
  margin-left: 10px;
  padding: 8px 16px;
  background-color: #d32f2f;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.user-stats {
  text-align: right;
  margin-bottom: 20px;
  color: #666;
}

.user-table-container {
  overflow-x: auto;
}

.user-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

.user-table th,
.user-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

.user-table th {
  background-color: #f5f5f5;
  font-weight: bold;
  color: #333;
}

.user-table tbody tr:hover {
  background-color: #f9f9f9;
}

.edit-btn, .delete-btn {
  padding: 6px 12px;
  margin: 0 5px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.edit-btn {
  background-color: #1976d2;
  color: white;
}

.edit-btn:hover {
  background-color: #1565c0;
}

.delete-btn {
  background-color: #d32f2f;
  color: white;
}

.delete-btn:hover {
  background-color: #c62828;
}

.add-user-button {
  text-align: center;
  margin-top: 20px;
}

.add-user-button button {
  padding: 12px 24px;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.add-user-button button:hover {
  background-color: #43a047;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 30px;
  border-radius: 8px;
  max-width: 500px;
  width: 90%;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-content h2 {
  margin-top: 0;
  color: #333;
}

.form-group {
  margin-bottom: 20px;
}

label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: #555;
}

input,
select {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  box-sizing: border-box;
}

.modal-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  margin-top: 20px;
}

.modal-actions button {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
}

.modal-actions button:first-child {
  background-color: #1976d2;
  color: white;
}

.modal-actions button:first-child:hover:not(:disabled) {
  background-color: #1565c0;
}

.modal-actions button:last-child {
  background-color: #757575;
  color: white;
}

.modal-actions button:last-child:hover:not(:disabled) {
  background-color: #616161;
}

.modal-actions button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.no-users {
  color: #888;
  font-style: italic;
}
</style>